package com.chensf.studydemo.common

import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.chensf.studydemo.R
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import kotlinx.android.synthetic.main.fragment_image_video.*
import java.io.File

class ImageFragment : Fragment() {
    private var index: Int = 1

    companion object {
        fun newInstance(resId: String, index: Int): ImageFragment {
            val fragment = ImageFragment()
            val bundle = bundleOf(
                Pair("resId", resId), Pair("index", index)
            )
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_image_video, container, false)
    }

    override fun onResume() {
        super.onResume()
        Log.e("ImageFragment", "onResume: $index")
    }

    override fun onPause() {
        super.onPause()
        Log.e("ImageFragment", "onPause: $index")
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val resId = arguments?.getString("resId")!!
        val root = Environment.getExternalStorageDirectory()

        index = arguments?.getInt("index")!!
        imageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CENTER_INSIDE)
        imageView.setMinimumTileDpi(160)
        val listener = DisplayOptimizeListener(imageView)
        imageView.setOnImageEventListener(listener)
        listener.setInitScaleType(DisplayOptimizeListener.INIT_SCALE_TYPE_CUSTOM)
        val bitmap = BitmapFactory.decodeFile(File(root,"testpic/$resId").absolutePath)
        imageView.setImage(ImageSource.bitmap(bitmap))
    }

}